﻿using Sidvall.AuthorizationManager.UI.ViewModels;
using Sidvall.Collections;
using Sidvall.IdentityManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.AuthorizationManager.UI
{
    public class Plugin : IPlugin
    {
        #region Public Members

        #region Title

        public string Title
        {
            get
            {
                return "Authorization";
            }
        }

        #endregion
        #region DefaultContext

        public string DefaultContext
        {
            get
            {
                return "data source=xxx;initial catalog=AuthorizationManager;user id=xxx;password=xxx";
            }
        }

        #endregion
        #region EditViewModelType

        public Type EditViewModelType
        {
            get
            {
                return typeof(UserViewModel);
            }
        }

        #endregion
        #region FilterViewModelType

        public Type FilterViewModelType
        {
            get
            {
                return typeof(FilterViewModel);
            }
        }

        #endregion
        #region DataColumnCaption1

        public string DataColumnCaption1
        {
            get
            {
                return "Authorization Scopes";
            }
        }

        #endregion
        #region DataColumnCaption2

        public string DataColumnCaption2
        {
            get
            {
                return null;
            }
        }

        #endregion
        #region DataColumnCaption3

        public string DataColumnCaption3
        {
            get
            {
                return null;
            }
        }

        #endregion

        #region DeleteUsersAsync

        public async Task<Sidvall.IdentityManager.Data.PluginResult> DeleteUsersAsync(IEnumerable<string> userIds)
        {
            if (userIds == null)
                return null;
            try
            {
                foreach (var userId in userIds)
                {
                    await Sidvall.AuthorizationManager.SystemContext.Current.DataPortal.AuthorizationScopeUserManager.DeleteItemsByUserIdAsync(userId);
                }
                return null;
            }
            catch (System.Exception ex)
            {
                return new Sidvall.IdentityManager.Data.PluginResult()
                {
                    Type = Sidvall.IdentityManager.Data.PluginResultType.Failed,
                    ErrorMessage = Sidvall.SystemContext.Current.SystemExceptionManager.GetMessage(ex),
                };
            }
        }

        #endregion
        #region GetUsersAsync

        public async Task<IdentityManager.Data.PluginFilterResult> GetUsersAsync(string pluginFilterContext, IEnumerable<string> userIds, string textFilter, int? rowCount, bool sortReversed)
        {
            Sidvall.AuthorizationManager.UI.Entities.AuthorizationScopeUserCollection items;
            Sidvall.IdentityManager.Data.PluginFilterResult result;
            Sidvall.AuthorizationManager.UI.Entities.FilterContext filter;
            Sidvall.IdentityManager.Data.PluginUser pluginUser;
            List<long> authorizationScopeIds;
            HashSet<string> ids;

            result = new Sidvall.IdentityManager.Data.PluginFilterResult()
            {
                Type = Sidvall.IdentityManager.Data.PluginFilterResultType.Update,
                Users = new Sidvall.IdentityManager.Data.PluginUserCollection(),
            };
            filter = Sidvall.AuthorizationManager.UI.Entities.FilterContext.Deserialize(pluginFilterContext);
            authorizationScopeIds = new List<long>();
            if (filter.AuthorizationScopeId != null)
            {
                authorizationScopeIds.Add(filter.AuthorizationScopeId.Value);
                if (!string.IsNullOrWhiteSpace(textFilter))
                    result.Type = Sidvall.IdentityManager.Data.PluginFilterResultType.UpdateRemove;
                else
                {
                    result.Type = Sidvall.IdentityManager.Data.PluginFilterResultType.UpdateRemoveAdd;
                    userIds = null;
                }
            }
            items = await Sidvall.AuthorizationManager.UI.SystemContext.Current.DataPortal.AuthorizationScopeUserManager.GetUsersAsync(null, authorizationScopeIds, userIds, null, false);
            if (authorizationScopeIds.Count > 0)
            {
                ids = (from o in items
                       select o.UserId).ToHashSet(o => o, true, System.StringComparer.OrdinalIgnoreCase);
                if (ids.Any())
                    items = await Sidvall.AuthorizationManager.UI.SystemContext.Current.DataPortal.AuthorizationScopeUserManager.GetUsersAsync(null, null, ids, null, false);
            }
            await items.LoadAuthorizationScopesAsync();
            foreach (var item in items)
            {
                pluginUser = result.Users.FindItemById(item.UserId);
                if (pluginUser != null)
                {
                    pluginUser.Data1 += System.Environment.NewLine + GetData(item);
                }
                else
                {
                    result.Users.Add(item.UserId, GetData(item));
                }
            }
            return result;
        }

        #endregion
        #region InitializeAsync

        public Task InitializeAsync(string context)
        {
            if (context.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                Sidvall.AuthorizationManager.SystemContext.Current.DataPortalStrategyFacade.ServerConnections.Clear();
                Sidvall.AuthorizationManager.SystemContext.Current.AddWebServiceConnection(context, null);
            }
            else
            {
                Sidvall.AuthorizationManager.SystemContext.Current.DataPortalStrategyFacade.ServerConnections.Clear();
                Sidvall.AuthorizationManager.SystemContext.Current.AddSqlServerConnection(context, null);
            }
            return Task.FromResult(true);
        }

        #endregion

        #endregion
        #region Private Members

        private string GetData(Sidvall.AuthorizationManager.UI.Entities.AuthorizationScopeUser item)
        {
            string value;

            if (item == null)
                return null;
            value = item.AuthorizationScope.Name;
            if (!item.IsActive)
                value += " (Inactive)";
            if (item.AccessTime == null)
                return value;
            return value + ": " + item.AccessTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
        }

        #endregion
    }
}
